package quan.dong.service;

import quan.dong.common.Common;
import quan.dong.common.Constant;
import quan.dong.handle.AlertListener;
import quan.dong.object.PriceAlert;
import quan.dong.pricealert.R;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

public class ListenerService extends Service {

	public static AlertListener alertListener;
	private final Handler handler = new Handler() {
		@Override
		public void dispatchMessage(Message msg) {
			// TODO Auto-generated method stub
			super.dispatchMessage(msg);
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			try {
				switch (msg.what) {
				case Constant.HANDLER_ALERT:
					PriceAlert alert = (PriceAlert) msg.obj;					
					String nofiticationTitle = String.format(
							getString(R.string.price_alert_notification_title),
							alert.getStockSymbol(), alert.getCurrentPrice());
					String notificationContent = "";
					if (alert.getIsAbove()) {
						String test=getString(R.string.above_price_alert);
						notificationContent = String.format(
								getString(R.string.above_price_alert), alert.getPrice());
					} else {
						notificationContent = String.format(
								getString(R.string.below_price_alert), alert.getPrice());
					}
					Common.showNofitication(getBaseContext(),
							getString(R.string.alert_tinker),
							nofiticationTitle, notificationContent, true);
					break;

				default:
					break;
				}

			} catch (Exception e) {
				e.getStackTrace();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO do something useful
		String imeiNumber = Common.GetImeiNumber(getBaseContext());
		alertListener = new AlertListener(imeiNumber, handler, "AlertListener");
		alertListener.Start();
		return Service.START_NOT_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}